const jwt = require('jsonwebtoken')
const consola = require('consola')
const requestLogger = (request, response, next) => {
  consola.info('Method:', request.method)
  consola.info('Path:  ', request.path)
  consola.info('Body:  ', request.body)
  consola.info('---')
  next()
}

const errorHandler = (error, request, response, next) => {
  if (error.name === 'CastError') {
    return response
      .status(200)
      .send({ data: null, msg: 'malformatted id', errno: 3 })
  } else if (error.name === 'ValidationError') {
    return response
      .status(200)
      .json({ data: null, msg: error.message, errno: 6 })
  } else if (error.name === 'JsonWebTokenError') {
    return response.status(401).json({
      data: null,
      msg: 'invalid token',
      errno: 2,
    })
  } else if (error.name === 'TokenExpiredError') {
    return response.status(401).json({
      data: null,
      msg: 'error',
      errno: 1,
    })
  }

  next(error)
}
const tokenExtractor = async (request, response, next) => {
  try {
    const authorization = request.get('Authorization')
    if (authorization && authorization.toLowerCase().startsWith('bearer ')) {
      const token = authorization.substring(7)
      console.time('tokenExtractor')
      const decodedToken = await jwt.verify(token, process.env.SECRET)
      console.timeEnd('tokenExtractor')
      request.userId = decodedToken.id
    }
    next()
  } catch (error) {
    next(error)
  }
}

//response.json 方法时，又调用了 response.json()，导致了死循环。要避免在重写的 response.json 方法中再次调用 response.json()。

const commonRes = (request, response, next) => {
  // 重写 res.json 方法
  const originalJson = response.json // 保存原始的 response.json 方法
  response.json = (data) => {
    console.log(
      '%c [ data ]-58',
      'font-size:13px; background:#7def35; color:#c1ff79;',
      data,
    )
    const { errno = 0, msg = '', ...result } = data
    originalJson.call(response, {
      errno,
      msg,
      data: result.data !== undefined ? result.data : data,
    })
  }
  next()
}

module.exports = { requestLogger, errorHandler, tokenExtractor, commonRes }
